package zmee.pur.src.formplugin;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2023/03/13/11:09
 * @Description: 填写【商务得分（实际值）】计算出【商务得分（100%）】
 */
public class ManualScoreBillPlugin extends AbstractBillPlugIn {

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        Object newValue = changeData.getNewValue();
        int rowIndex = changeData.getRowIndex();
        if ("zmee_bizscore".equals(name) && Objects.nonNull(newValue)) {
            Object parentId = this.getModel().getValue("parentid");
            QFilter filter = new QFilter("parentid", QCP.equals, parentId);
            //评标设置
            DynamicObject bidOpenConfig = BusinessDataServiceHelper.loadSingle("src_bidopen_config", "entryentity.indextype,entryentity" +
                    ".weight", filter.toArray());
            if (bidOpenConfig != null) {
                DynamicObjectCollection entryEntity = bidOpenConfig.getDynamicObjectCollection("entryentity");
                if (!entryEntity.isEmpty()) {
                    //过滤获得商务权重
                    List<DynamicObject> collect = entryEntity.stream().filter(entity -> "SYS002".equals(entity.getDynamicObject(
                            "indextype").getString("number"))).collect(Collectors.toList());
                    if (collect.size() > 0) {
                        //权重
                        BigDecimal weight = collect.get(0).getBigDecimal("weight");
                        weight = weight.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
                        // 实际值 / 权重
                        BigDecimal bizScore = ((BigDecimal) newValue).divide(weight, 2, RoundingMode.HALF_UP);
                        this.getModel().setValue("bizscore", bizScore, rowIndex);
                    }
                }
            }
        }
    }
}
